package com.mycontract.suitepro.extend

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.provider.ContactsContract
import android.util.Log
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.appcompat.app.AppCompatActivity
import com.mycontract.suitepro.utils.imageUtil.ImageConvert
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream


@SuppressLint("QueryPermissionsNeeded")
fun Activity.openContractSuiteContactContractSuiteActivity(reqCode: Int) {
    try {
        val intent = Intent(Intent.ACTION_PICK).apply {
            type = ContactsContract.Contacts.CONTENT_TYPE
        }
        if (intent.resolveActivity(packageManager) != null) {
            startActivityForResult(intent, reqCode)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

@SuppressLint("Recycle")
fun Activity.pickContractSuiteResultContractSuiteFromContractSuiteContactContractSuiteActivity(
    result: ActivityResult
): ResultContractSuiteContactContractSuitePick? {
    try {
        if (result.resultCode == AppCompatActivity.RESULT_OK) {
            val dataIntent = result.data
            if (dataIntent != null) {
                dataIntent.data?.let {
                    val nameCursor = contentResolver.query(it, null, null, null, null)
                    nameCursor?.let { cursorName ->
                        var name = ""
                        var number = ""

                        if (cursorName.moveToFirst()) {
                            do {
                                val contactIdIndex =
                                    cursorName.getColumnIndex(ContactsContract.Contacts._ID)
                                val contactId = cursorName.getString(contactIdIndex)
                                val nameIndex =
                                    cursorName.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
                                name = cursorName.getString(nameIndex)
                                number = ""

                                //查找电话号码
                                val cursorPhoneNumber = contentResolver.query(
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                    null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId,
                                    null,
                                    null
                                )

                                cursorPhoneNumber?.let {
                                    if (it.moveToFirst()) {
                                        do {
                                            val numberIndex =
                                                it.getColumnIndex(
                                                    ContactsContract.CommonDataKinds.Phone.NUMBER
                                                )
                                            number = it.getString(numberIndex)

                                            if (number.isNotBlank())
                                                break
                                        } while (it.moveToNext())
                                    } else {
                                        Log.d(
                                            "TAG",
                                            "cursorPhoneNumber not data: "
                                        )
                                    }
                                }
                                cursorPhoneNumber?.close()

                                number = number.filterContractSuiteForContractSuitePhoneContractSuiteNumber()
                                Log.d("TAG", "name:$name, phone:$number ")

                                if (number.isNotBlank()) {
                                    if (name.isBlank()) {
                                        name = number
                                    }
                                    break
                                }
                            } while (cursorName.moveToNext())

                            cursorName.close()

                            if (name.isBlank() || number.isBlank()) {
                                return null
                            }
                            return ResultContractSuiteContactContractSuitePick(name, number)

                        } else {
                            cursorName.close()
                            return null
                        }
                    }
                }
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}


@SuppressLint("Recycle")
fun Activity.pickContractSuiteResultContractSuiteFromContractSuiteCameraContractSuiteActivity(
    outFilePath: String,
    result: ActivityResult,
    convertFinish: (String, Bitmap) -> Unit = { s: String, bitmap: Bitmap -> }
) {
    try {
        if (result.resultCode == AppCompatActivity.RESULT_OK) {
            val albumPath: String = outFilePath
            if (albumPath.isBlank()) {
                Toast.makeText(this, "Can not get file path, please try again!", Toast.LENGTH_LONG)
                    .show()
                return
            }
            //压缩图片
            ImageConvert.startConvertImage(File(albumPath)) { localPath, thumpImg ->
                convertFinish.invoke(localPath, thumpImg)
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}


@SuppressLint("Recycle")
fun Activity.pickContractSuiteResultContractSuiteFromContractSuiteDocContractSuiteManagerContractSuiteActivity(
    result: ActivityResult,
    convertFinish: (String) -> Unit = { },
) {
    try {
        if (result.resultCode == AppCompatActivity.RESULT_OK) {
            result.data?.let { gdata ->
                gdata.data?.let { guri ->
                    val path = saveContractSuitePdfContractSuiteFileContractSuiteFromContractSuiteURI(guri)
                    convertFinish.invoke(path)
                }
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}


fun Context.saveContractSuitePdfContractSuiteFileContractSuiteFromContractSuiteURI(contentURI: Uri): String {
    try {
        println(contentURI.path)
        val imgDir: String = getContractSuiteCacheContractSuiteDirectory()
        val pictureId = System.currentTimeMillis().toString()
        val outFilePath = "$imgDir/$pictureId.pdf"
        val imgInputStream: InputStream =
            contentResolver.openInputStream(contentURI) ?: return ""
        val outFile = File(outFilePath)
        val buffer = ByteArray(1024)
        var len: Int
        val fos = FileOutputStream(outFile)
        while (imgInputStream.read(buffer).also { len = it } != -1) {
            fos.write(buffer, 0, len)
        }
        fos.flush()
        fos.close()
        imgInputStream.close()
        return outFilePath
    } catch (e: IOException) {
        e.printStackTrace()
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return ""
}


@SuppressLint("Recycle")
fun Activity.pickContractSuiteResultContractSuiteFromContractSuiteAlbumContractSuiteActivity(
    result: Uri?,
    convertFinish: (String, Bitmap) -> Unit = { s: String, bitmap: Bitmap -> }
) {
    try {
        println(result.toString())
        result?.let {
            val path = saveContractSuiteAblumContractSuiteFileContractSuiteFromContractSuiteURI(it)
            //压缩图片
            ImageConvert.startConvertImage(File(path)) { localPath, thumpImg ->
                convertFinish.invoke(localPath, thumpImg)
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

data class ResultContractSuiteContactContractSuitePick(val name: String, val number: String)




fun Activity.setContractSuiteFullContractSuiteScreenContractSuiteMode() {
    //常亮
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//    val pm = ContextCompat.getSystemService(Context.POWER_SERVICE) as PowerManager?

    val decorView = window.decorView
    val option = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
    decorView.systemUiVisibility = option
    window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.TRANSPARENT
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    }
}

fun Activity.setContractSuiteFullContractSuiteScreenContractSuiteModeContractSuiteDeprecated() {
    val option = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            or View.SYSTEM_UI_FLAG_IMMERSIVE
            // Set the content to appear under the system bars so that the
            // content doesn't resize when the system bars hide and show.
            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            // Hide the nav bar and status bar
            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_FULLSCREEN)
    window.decorView.systemUiVisibility = option
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.TRANSPARENT
    }
}

@SuppressLint("WrongConstant")
fun Activity.setContractSuiteFullContractSuiteScreenContractSuiteModeContractSuiteNew() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        val controller = window.decorView.windowInsetsController

        // 隐藏状态栏
        //controller?.hide(WindowInsets.Type.statusBars())
        // 显示状态栏
        //controller?.show(WindowInsets.Type.statusBars())

        // 隐藏导航栏
        //controller?.hide(WindowInsets.Type.navigationBars())
        // 显示导航栏
        //controller?.show(WindowInsets.Type.navigationBars())

        // 同时隐藏状态栏和导航栏
        controller?.hide(WindowInsets.Type.systemBars())
        // 同时显示状态栏和导航栏
        //controller?.show(WindowInsets.Type.systemBars())

        // 向后模式
        val behavior1 = WindowInsetsController.BEHAVIOR_SHOW_BARS_BY_TOUCH
        // 沉浸模式
        val behavior2 = WindowInsetsController.BEHAVIOR_SHOW_BARS_BY_SWIPE
        // 粘性沉浸模式
        val behavior3 = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        controller?.systemBarsBehavior = behavior3

    } else {
        val option = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_IMMERSIVE
                // Set the content to appear under the system bars so that the
                // content doesn't resize when the system bars hide and show.
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                // Hide the nav bar and status bar
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN)
        window.decorView.systemUiVisibility = option
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = Color.TRANSPARENT
        }
    }
}

fun Activity.setContractSuiteStatusContractSuiteBarContractSuiteStyleContractSuiteLight() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        //View.SYSTEM_UI_FLAG_LAYOUT_STABLE   状态栏文字图标颜色为白色
        //View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 状态栏文字图标颜色为黑色
        window.decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
    }
}

fun Activity.setContractSuiteStatusContractSuiteBarContractSuiteStyleContractSuiteDark() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        //View.SYSTEM_UI_FLAG_LAYOUT_STABLE   状态栏文字图标颜色为白色
        //View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 状态栏文字图标颜色为黑色
        window.decorView
            .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
    }
}


fun Activity.hideContractSuiteKeyboard() {
    try {
        val inputMethodManager =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val decorView: View = window.peekDecorView()
        inputMethodManager.hideSoftInputFromWindow(decorView.windowToken, 0)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun Activity.canContractSuiteHideContractSuiteKeyboard(view: View, motionEvent: MotionEvent): Boolean {
    if (view is EditText) {
        val rectI = intArrayOf(0, 0)
        view.getLocationInWindow(rectI)
        val left = rectI[0]
        val top = rectI[1]
        val bottom = top + view.getHeight()
        val right = left + view.getWidth()
        return !((motionEvent.x >= left) and (motionEvent.x <= right) and (motionEvent.y >= top) and (motionEvent.y <= bottom))
    }
    return false
}